//
//  AppDelegate.m
//  zhixinApp
//
//  Created by zhiguanzhl on 2017/11/11.
//  Copyright © 2017年 zhiguanzhl. All rights reserved.
//

#import "AppDelegate.h"
#import "CDTabbarVC.h"
#import "LoginViewController.h"
#import "CDNavigationVC.h"
#import <UserNotifications/UserNotifications.h>


@interface AppDelegate ()<EMChatManagerDelegate>
@property (nonatomic, strong) CDTabbarVC *tabbar;


@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.tabbar = [[CDTabbarVC alloc] init];
    self.window.rootViewController = self.tabbar;
    self.tabbar.selectedIndex = 2;
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    //初始化环信
    [self createHx:application withLaunching:launchOptions];

    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"userInfoModal"] length]>0) {
        
        //解归档，给用户信息单例复值
        [self getUserInfo];
        
         NSString *passWord = [[NSUserDefaults standardUserDefaults]valueForKey:@"passWord"];
        
        //登陆环信
        [ZLHXHelper loginHXWithPw:passWord];
        
    }else {
        //弹出登陆
        LoginViewController *loginVc = [[LoginViewController alloc] init];
//        self.window.rootViewController = [[CDNavigationVC alloc] initWithRootViewController:[[LoginViewController alloc]init]];
        
         [[UIApplication sharedApplication].delegate.window.rootViewController presentViewController:loginVc animated:YES completion:nil];
    }
    
    IQKeyboardManager *keyboardManager = [IQKeyboardManager sharedManager];
    keyboardManager.enableAutoToolbar = NO;
    keyboardManager.shouldResignOnTouchOutside = YES;
    keyboardManager.shouldToolbarUsesTextFieldTintColor = YES; // 控制键盘上的工具条文字颜色是否用户自定义
    
    keyboardManager.toolbarManageBehaviour = IQAutoToolbarBySubviews; // 有多个输入框时，可以通过点击Toolbar 上的“前一个”“后一个”按钮来实现移动到不同的输入框
    keyboardManager.toolbarTintColor = [UIColor grayColor];
    keyboardManager.enableAutoToolbar = NO; // 控制是否显示键盘上的工具条
    keyboardManager.keyboardDistanceFromTextField = 10.0f; // 输入框距离键盘的距离
    
    return YES;
}


#pragma mark - 环信
- (void)createHx:(UIApplication *)application withLaunching:(NSDictionary *) launchOptions {
    
    //环信
    EMOptions *options = [EMOptions optionsWithAppkey:KHXKey];
    
    options.apnsCertName = KHXCer;
    [[EMClient sharedClient] initializeSDKWithOptions:options];
    
    EMGroupOptions *option = [[EMGroupOptions alloc] init];
//    若NO，被邀请的人自动加入群组
    option.IsInviteNeedConfirm = NO;
    
    //初始化esaeUI
    [ZLHXHelper easeUIApplication:application withOptions:launchOptions];
    
    //注册离线通知
    [ZLHXHelper registerNoti];
    
    //注册消息回调
    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
}

// 将得到的deviceToken传给SDK
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    [[EMClient sharedClient] bindDeviceToken:deviceToken];
}

// 注册deviceToken失败
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    NSLog(@"error -- %@",error);
}

// 收到消息的回调，带有附件类型的消息可以用 SDK 提供的下载附件方法下载（后面会讲到）
- (void)messagesDidReceive:(NSArray *)aMessages {
//    [ZLHXHelper receiveMessage:aMessages];
     [[NSNotificationCenter defaultCenter] postNotificationName:@"messagesDidReceive" object:nil];
    
    
    dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{
        
        for(EMMessage *message in aMessages){
            UIApplicationState state = [[UIApplication sharedApplication] applicationState];
            switch (state) {
                case UIApplicationStateBackground:
                    [self showNotificationWithMessage:message];
                    break;
                default:
                    break;
            }
        }
    });
    
}




- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    [[EMClient sharedClient] applicationDidEnterBackground:application];
    
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    [[EMClient sharedClient] applicationWillEnterForeground:application];
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

// 申请处理时间
- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
     
}

- (void)getUserInfo{
    
    NSData *data = [[NSUserDefaults standardUserDefaults]valueForKey:@"userInfoModal"];
    NSDictionary  *userDic = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    UserInfoModel *userModal = [UserInfoModel mj_objectWithKeyValues:userDic];
    [DataCenter shareInstence].companyList = userModal.companyList;
    [DataCenter shareInstence].mobile = userModal.mobile;
    [DataCenter shareInstence].loginName = userModal.loginName;
    [DataCenter shareInstence].name = userModal.name;
//    for (CompanyModel *companyModal in userModal.companyList) {
//
//        [DataCenter shareInstence].companyId = companyModal.companyId;
//        [DataCenter shareInstence].companyName = companyModal.name;
//
//    }
    
}
- (void)showNotificationWithMessage:(EMMessage *)message
{
    EMPushOptions *options = [[EMClient sharedClient] pushOptions];
    NSString *alertBody = nil;
    if (options.displayStyle == EMPushDisplayStyleMessageSummary) {
        EMMessageBody *messageBody = message.body;
        NSString *messageStr = nil;
        switch (messageBody.type) {
            case EMMessageBodyTypeText:
            {
                messageStr = ((EMTextMessageBody *)messageBody).text;
            }
                break;
            case EMMessageBodyTypeImage:
            {
                messageStr = NSLocalizedString(@"message.image", @"Image");
            }
                break;
            case EMMessageBodyTypeLocation:
            {
                messageStr = NSLocalizedString(@"message.location", @"Location");
            }
                break;
            case EMMessageBodyTypeVoice:
            {
                messageStr = NSLocalizedString(@"message.voice", @"Voice");
            }
                break;
            case EMMessageBodyTypeVideo:{
                messageStr = NSLocalizedString(@"message.video", @"Video");
            }
                break;
            default:
                break;
        }
        
        do {
            NSString *title = message.from;
            if (message.chatType == EMChatTypeGroupChat) {
                NSDictionary *ext = message.ext;
                if (ext && ext[kGroupMessageAtList]) {
                    id target = ext[kGroupMessageAtList];
                    if ([target isKindOfClass:[NSString class]]) {
                        if ([kGroupMessageAtAll compare:target options:NSCaseInsensitiveSearch] == NSOrderedSame) {
                            alertBody = [NSString stringWithFormat:@"%@%@", title, NSLocalizedString(@"group.atPushTitle", @" @ me in the group")];
                            break;
                        }
                    }
                    else if ([target isKindOfClass:[NSArray class]]) {
                        NSArray *atTargets = (NSArray*)target;
                        if ([atTargets containsObject:[EMClient sharedClient].currentUsername]) {
                            alertBody = [NSString stringWithFormat:@"%@%@", title, NSLocalizedString(@"group.atPushTitle", @" @ me in the group")];
                            break;
                        }
                    }
                }
                NSArray *groupArray = [[EMClient sharedClient].groupManager getJoinedGroups];
                for (EMGroup *group in groupArray) {
                    if ([group.groupId isEqualToString:message.conversationId]) {
                        title = [NSString stringWithFormat:@"%@(%@)", message.from, group.subject];
                        break;
                    }
                }
            }
            
            
            alertBody = [NSString stringWithFormat:@"%@:%@", title, messageStr];
        } while (0);
    }
    else{
        alertBody = NSLocalizedString(@"receiveMessage", @"you have a new message");
    }
//    NSTimeInterval timeInterval = [[NSDate date] timeIntervalSinceDate:self.lastPlaySoundDate];
//    BOOL playSound = NO;
//    if (!self.lastPlaySoundDate || timeInterval >= kDefaultPlaySoundInterval) {
//        self.lastPlaySoundDate = [NSDate date];
//        playSound = YES;
//    }
    
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
    [userInfo setObject:[NSNumber numberWithInt:message.chatType] forKey:@"MessageType"];
    [userInfo setObject:message.conversationId forKey:@"ConversationChatter"];
    //发送本地推送
    if (NSClassFromString(@"UNUserNotificationCenter")) {
        if (@available(iOS 10.0, *)) {
            UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:0.01 repeats:NO];
        } else {
            // Fallback on earlier versions
        }
        if (@available(iOS 10.0, *)) {
            UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
            content.body =alertBody;
            content.userInfo = userInfo;
            UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:message.messageId content:content trigger:nil];
            [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:nil];
        }
       
        
    }
    else {
        UILocalNotification *notification = [[UILocalNotification alloc] init];
        notification.fireDate = [NSDate date]; //触发通知的时间
        notification.alertBody = alertBody;
        notification.alertAction = NSLocalizedString(@"open", @"Open");
        notification.timeZone = [NSTimeZone defaultTimeZone];
//        if (playSound) {
//            notification.soundName = UILocalNotificationDefaultSoundName;
//        }
        notification.userInfo = userInfo;
        
        //发送通知
        [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    }
}

@end
